<template>
  <div class="search">
    <van-nav-bar title="搜索中心" left-arrow @click="$router.back()"></van-nav-bar>

     <!-- 搜索框 -->
     <van-search
      v-model.trim="value"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @input="onInput"
      @search="onSearch(keyword)"
    >
      <template #action>
        <div @click="onSearch(keyword)">搜索</div>
      </template>
    </van-search>

    <!-- 推荐 -->
    <van-cell-group v-if="value">
      <van-cell
    icon="search"
    v-for="(item, index) in sugList"
    :key="index"
    @click=onSearch(item)
    >
    <span v-html="highLight(item, value)"></span>
  </van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group v-else>
  <van-cell title="历史记录"></van-cell>
  <van-cell
  :title="ele"
  v-for="ele in history"
  :key="ele">
    <van-icon
    @click.stop="del(item)"
    name="close" />
  </van-cell>
</van-cell-group>
  </div>
</template>

<script>
import { getSuggest } from '@/api/search'
export default {
  name: 'Search',
  data () {
    return {
      value: '',
      sugList: [],
      history: ['思聪', '经典语录', 'test', '美女', 'javascript', 'java']
    }
  },
  methods: {
    onInput() {
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (!this.value) return
        const res = await getSuggest(this.value)
        if (res.data.options[0] === null) {
          return (this.sugList = [])
        }
        this.sugList = res.data.options
      }, 800)
    },

    onSearch(value) {
      if (!value) return this.$toast('请输入关键字')
      // 添加历史记录
      this.history = this.history.filter(item => item !== value)
      this.history.unshift(value)
      // 最后需要跳转到搜索结果页面
      this.$router.push({
        path: '/result',
        query: {
          keyword: value
        }
      })
      console.log('跳转', value)
    },
    highLight (str, keyword) {
      const reg = new RegExp(keyword, 'gi')
      return str.replace(reg, match => {
        return `<span style="color: red">${match}</span>`
      })
    }
  }
}
</script>

<style lang="less" scoped>
.van-nav-bar {
  background-color: #3196fa;

  .van-nav-bar__title,
  .van-icon {
    color: #fff;
  }
}

</style>
